package com.meiyou.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.meiyou.mapper.MeiyouChongzhiMapper;
import com.meiyou.mapper.MeiyouSettingMapper;
import com.meiyou.mapper.MeiyouTixianMapper;
import com.meiyou.mapper.MeiyouUserMapper;
import com.meiyou.mapper.MeiyouZfbMapper;
import com.meiyou.pojo.AliPayInfo;
import com.meiyou.pojo.Chongzhi;
import com.meiyou.pojo.MeiyouChongzhi;
import com.meiyou.pojo.MeiyouSetting;
import com.meiyou.pojo.MeiyouSettingExample;
import com.meiyou.pojo.MeiyouThir;
import com.meiyou.pojo.MeiyouTixian;
import com.meiyou.pojo.MeiyouUser;
import com.meiyou.pojo.MeiyouZfb;
import com.meiyou.pojo.MeiyouZfbExample;
import com.meiyou.service.AlipayService;
import com.meiyou.service.TecentService;
import com.meiyou.service.ThirdService;
import com.meiyou.utils.Context;
import com.meiyou.utils.GenerateOrderNoUtil;
import com.meiyou.utils.Msg;
import com.meiyou.utils.ShareCodeUtil;
import com.meiyou.utils.StatusCode;

@Service
public class AliPayServiceImpl implements AlipayService {

	@Autowired
	MeiyouUserMapper usermapper;
	@Autowired
	TecentService tencentService;
	@Autowired
	ThirdService thirdService;
	@Autowired
	MeiyouChongzhiMapper chongzhiMapper;
	@Autowired
	MeiyouZfbMapper zfbMapper;
	@Autowired
	MeiyouTixianMapper tixianMapper;
	@Autowired
	MeiyouSettingMapper settingMapper;

	/**
	 * @author dengshilin 支付宝登录业务，获取支付宝信息
	 */

	public Msg getAliPayInfo(String code) {
		AlipayClient alipayClient = new DefaultAlipayClient(Context.SXALIURL, Context.SXAPPID,
				Context.SXAPP_PRIVATE_KEY, Context.SXFORMAT, Context.SXCHARSET, Context.SXALIPAY_PUBLIC_KEY,
				Context.SXSIGN_TYPE); // 调用接口之前的初始化

		// TODO Auto-generated method stub
		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();// 初始化请求
		request.setGrantType("authorization_code");// 值为authorization_code时，代表用code换取；值为refresh_token时，代表用refresh_token换取
		request.setCode(code);// 参数为授权码

		try {
			AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
			if (response.isSuccess()) { // 判断换取授权访问令牌接口调用是否成功
				System.out.print(response.getBody());
				String access_token = response.getAccessToken();// 访问令牌,通过该令牌调用需要用户信息授权的接口，如alipay.user.info.share
				System.out.println("授权令牌：" + access_token);
				AlipayUserInfoShareRequest request1 = new AlipayUserInfoShareRequest();
				AlipayUserInfoShareResponse response1 = alipayClient.execute(request1, access_token);

				if (response1.isSuccess()) {
					Map<String, Object> map = new HashMap<String, Object>();
					AliPayInfo alipayinfo = new AliPayInfo();
					System.out.println("支付宝id" + response1.getUserId());
					alipayinfo.setUserId(response1.getUserId()); // 支付宝id
					alipayinfo.setAvatar(response1.getAvatar()); // 支付宝头像URL
					alipayinfo.setGender(response1.getGender()); // 支付宝性别
					System.out.println("手机号" + response1.getPhone());//
					alipayinfo.setIs_certied(response1.getIsCertified()); // 支付宝是否实名
					alipayinfo.setNick_name(response1.getNickName()); // 支付宝昵称
					map.put("alipayinfo", alipayinfo);
					Msg msg = Msg.success();
					msg.setExtend(map);
					System.out.println("调用成功" + ",msg:" + msg.toString());
					return msg;
				} else {
					System.out.println("错误码" + response1.getCode());
					System.out.println("明细错误码" + response1.getSubCode());
					System.out.println("调用失败!" + response1.getMsg());
				}
			} else {
				Msg msg = Msg.fail();
				msg.setMsg("请求失败，授权码可能错误!请检查!!");
				return msg;
			}
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Msg msg = Msg.fail();
		return msg;
	}

	/**
	 * 获取支付订单信息
	 */
	public String getOrderInfo(String total_amount, String subject, String out_trade_no, HttpServletRequest req) {

		// TODO Auto-generated method stub
		if (req.getSession().getAttribute("user") == null) {
			return "login";
		} else {
			MeiyouChongzhi chongzhi = new MeiyouChongzhi();
			chongzhi.setcCzcode(out_trade_no);  
			chongzhi.setcUCount(req.getSession().getAttribute("user").toString());
			Double bili = Double.parseDouble(settingMapper.selChongzhiBili());
			Double cz = Double.parseDouble(total_amount);
			chongzhi.setcMeijin((int)(cz+cz*bili));
			chongzhi.setcTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			chongzhi.setcPaytype("支付宝");
			chongzhi.setcState("未支付");
			int zhuangtai = chongzhiMapper.insertSelective(chongzhi);
			if (zhuangtai == 1) {
				Msg msg;
				AlipayClient alipayClient = new DefaultAlipayClient(Context.SXALIURL, Context.SXAPPID,
						Context.SXAPP_PRIVATE_KEY, "json", Context.SXCHARSET, Context.SXALIPAY_PUBLIC_KEY, "RSA2"); // 获得初始化的AlipayClient
				AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();// 创建API对应的request
				alipayRequest.setReturnUrl(Context.fwqaddress + "/payCallback");// 异步通知
				alipayRequest.setNotifyUrl(Context.fwqaddress + "/alipayReturnNotice");// 在公共参数中设置回跳和通知地址
				alipayRequest.setBizContent("{" + " \"out_trade_no\":\"" + out_trade_no + "\"," + " \"total_amount\":\""
						+ total_amount + "\"," + " \"subject\":\"" + subject + "\","
						+ " \"product_code\":\"QUICK_WAP_PAY\"" + " }");// 填充业务参数
				String form = "";
				try {
					form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
				} catch (AlipayApiException e) {
					e.printStackTrace();
				}
				return form;
			}
		}
		return null;
	}

	/**
	 * 查找是个存在该支付宝用户
	 */
	public boolean alipayHas(String alipayid) {
		// TODO Auto-generated method stub
		if (usermapper.getcountByalipay(alipayid) == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 通过支付登录自动注册
	 */
	public Msg insRegistByAlipay(String phone, String imgurl, String alipayid, String sex, String uname) {
		Msg msg;
		// TODO Auto-generated method stub
		if (usermapper.getcountByalipay(alipayid) == 1) {
			msg = Msg.fail();
			msg.setMsg("支付宝已经绑定了账户");
			return msg;
		} else {
			MeiyouThir thir = new MeiyouThir();
			thir.settZfbcount(alipayid);
			String ucount = ShareCodeUtil.getRamdomCount();
			thir.settUCount(ucount);
			if (thirdService.insThirdSelective(thir) == 1) { // 插入第三方支付宝信息和用户信息
				MeiyouUser user = new MeiyouUser();
				user.setuCount(ucount);
				user.setuImg(imgurl);
				user.setuName(uname);
				user.setuSex(sex);
				user.setuPhone(phone);
				String time = new SimpleDateFormat("hhhh-MM-dd HH:mm:ss").format(new Date());
				user.setuTime(time);
				user.setUmeijin(0);
				if (usermapper.insertSelective(user) == 1) { // 腾讯云通讯账户注册
					if (tencentService.registTencent(user)) {
						msg = Msg.success();
						return msg;
					} else {
						msg = Msg.fail();
						msg.setMsg("通讯云IM账户注册失败");
						return msg;
					}
				}
			} else {
				msg = Msg.fail();
				msg.setMsg("服务器异常");
			}
			msg = Msg.fail();
			return msg;

		}

	}

	/**
	 * 支付宝申请提现
	 */
	public Msg zfbTixian(String uccount, double num) {
		Msg msg;
		// TODO Auto-generated method stub
		double has = usermapper.selMeijin(uccount);
		if (has >= num) {
			if (usermapper.updDelMeijin(num, uccount) >= 1) {
				AlipayClient alipayClient = new DefaultAlipayClient(Context.SXALIURL, Context.SXAPPID,
						Context.SXAPP_PRIVATE_KEY, Context.SXFORMAT, Context.SXCHARSET, Context.SXALIPAY_PUBLIC_KEY,
						Context.SXSIGN_TYPE); // 调用接口之前的初始化
				MeiyouZfbExample example = new MeiyouZfbExample();
				MeiyouZfbExample.Criteria criteria = example.createCriteria();
				criteria.andZUCountEqualTo(uccount);
				List<MeiyouZfb> list = zfbMapper.selectByExample(example);
				if (list.size() == 0) {
					msg = Msg.fail();
					msg.setMsg("未绑定支付宝");
				} else {
					MeiyouZfb zfb = list.get(0);
					MeiyouSettingExample example1 = new MeiyouSettingExample();
					MeiyouSettingExample.Criteria criteria1 = example1.createCriteria();
					criteria1.andJNameEqualTo("tixian");
					MeiyouSetting setting = settingMapper.selectByExample(example1).get(0);
					double txfl = Double.parseDouble(setting.getjValue());// 提现收费率
					String meijin = String.valueOf(num *(((double)1 - txfl)));
					AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
					String tx_order = getOrderIdByUUId();
					System.out.println("提现订单号："+tx_order);
					System.out.println("支付宝账号："+zfb.getzCount());
					System.out.println("支付宝提现美金"+meijin);
					System.out.println("支付宝名字："+zfb.getzName());
					request.setBizContent("{" + "\"out_biz_no\":\"" + tx_order + "\","
							+ "\"payee_type\":\"ALIPAY_LOGONID\"," + "\"payee_account\":\"" + zfb.getzCount() + "\","
							+ "\"amount\":\"" + meijin + "\"," + "\"payer_show_name\":\"美游提现\","
							+ "\"payee_real_name\":\"" + zfb.getzName() + "\"," + "\"remark\":\"提现\"" + "  }");
					try {
						AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
						if (response.isSuccess()) {

							// 提现成功后添加提现记录
							MeiyouTixian tixian = new MeiyouTixian();
							tixian.settUCount(uccount);
							tixian.settDdcode(tx_order);
							tixian.settSdmeijin(num * (1 - txfl));
							tixian.settState(true);
							tixian.settTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
							tixian.settFangshi("支付宝");
							tixian.settMeijin(num);
							tixian.settShenhe("通过");
							if (tixianMapper.insertSelective(tixian) >= 1) {
								msg = Msg.success();
								return msg;
							}
						} else {
							System.out.println("调用失败");
							msg = Msg.fail();
							return msg;
						}
					} catch (AlipayApiException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} else {
			msg = Msg.fail();
			msg.setMsg("账号余额不足");
			return msg;
		}
		msg = Msg.fail();
		return msg;
	}

	public static String getOrderIdByUUId() {
		int machineId = 1;// 最大支持1-9个集群机器部署
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {
			hashCodeV = -hashCodeV;
		}
		return machineId + String.format("%015d", hashCodeV);
	}

}
